import { Injectable } from "@angular/core";
import { Duration } from "@fullcalendar/common";
import { WorkFlowProcessDto, WorkFlowProcessMsgDto } from "@shared/service-proxies/service-proxies";
import { DateTime } from "luxon";
import { DateTimeService } from "../timing/date-time.service";
import { UserHelper } from "./user-helper.service";
import { IRemarkDataItem, ITranslateItem } from "./workflow-common-interface";


@Injectable()
export class WorkFlowHelper {

    constructor(private _dateTimeService: DateTimeService,
        private _userHelper:UserHelper){

    }
    /**
     * 时分秒格式化
     * @param {long} value  时间差
     * @returns  {string} XX 小时 XX 分 XX 秒
     */
    formatSeconds(value:string):string {
        let theTime = Number.parseInt(value);// 秒
        let theTime1 = 0;// 分
        let theTime2 = 0;// 小时
        if (theTime > 60) {
            theTime1 = Math.floor(theTime / 60);
            theTime = Math.floor(theTime % 60);
            if (theTime1 > 60) {
                theTime2 = Math.floor(theTime1 / 60);
                theTime1 = Math.floor(theTime1 % 60);
            }
        }
        let result = "" + Math.floor(theTime) + "秒";
        if (theTime1 > 0) {
            result = "" + Math.floor(theTime1) + "分" + result;
        }
        if (theTime2 > 0) {
            if (theTime2 > 24) {
                result = "" + Math.floor(theTime2 / 24) + "天" + Math.floor(theTime % 24) + "小时" + result;
            } else {
                result = "" + Math.floor(theTime2) + "小时" + result;
            }
        }
        return result;
    }

    /**
     * 
     * @param time 时间
     */
    timeFormat(time?:DateTime | string): string {
        if (!time) return "";
        if (typeof time === "string"){
            return this._dateTimeService.fromISODateString(time).toFormat('yyyy/MM/dd HH:mm:ss');
        }
        else{ 
            return time.toFormat('yyyy/MM/dd HH:mm:ss');
        }
    }

    /**
     * 
     * @param state 
     * @param markTime 
     * @param finishedTime 
     * @returns 
     */
    timeDiffCalc(state:number,markTime?:DateTime,finishedTime?:DateTime){
        let str = "";
        if (!markTime) return str;

        if (typeof markTime == 'string'){
            let markTimeData = this._dateTimeService.convertDateFromString(markTime,'/');
            markTime = this._dateTimeService.fromJSDate(markTimeData);
        }
        if (finishedTime && typeof finishedTime == 'string'){
            let finishedTimeData = this._dateTimeService.convertDateFromString(finishedTime,'/');
            finishedTime = this._dateTimeService.fromJSDate(finishedTimeData);
        }
         
        if (state != 2) return str;
        let startTime = markTime;
        let endTime = finishedTime ? finishedTime : this._dateTimeService.getDate();
        //let seconds:Duration = this._dateTimeService.getDiffInSeconds(endTime,startTime);
        let msecods = endTime.diff(startTime).toObject();
        let s = 0;
        if ( msecods.milliseconds && msecods.milliseconds > 0){
            s = msecods.milliseconds / 1000;
        }
      
        return ",用时： " + this.formatSeconds(s.toString());
    }

    /**
     * 
     * @param data 
     * @returns 
     */
    checkState(data: ITranslateItem){
        switch (data.state) {
            case 0:
                return "等待";
            case 1:
                if (data.operationType === 0) {
                    return "待阅";
                } else {
                    return "待办";
                }
            case 2:
                if (data.operationType === 0) {
                    return data.hasRead? "已阅" : "未阅";
                } else {
                    if (data.finishedTime) {
                        return "已办理";
                    } else {
                        return "已取消";
                    }
                }
            case 4:
                return "已取消";
        }
        return "";
    }

      /**
            * 格式化流程轨迹
            * @param {Array} arr 原始数据
            * @param {Array} additionalMsg 附加意见
            * @return {Array} 目标数组
            */
    getRemarkData(arr: WorkFlowProcessDto[], additionalMsg: WorkFlowProcessMsgDto[]): IRemarkDataItem[]{
        let remarkData = [];
        if (!arr) {
            return remarkData;
        }

        let currentName = null;
        arr.forEach(value=> {
            if (value.nodeName) {
                if (value.nodeName != currentName) {
                    //新一步骤
                    currentName = value.nodeName;
                    if (remarkData.length > 0) {
                        remarkData[remarkData.length - 1].isOpen = false; 
                    }
                    let ob:IRemarkDataItem = { nodeName: currentName, isOpen: true, data: [] };
                    ob.data = [this.translateItem(value, 0, additionalMsg)];
                    remarkData.push(ob);
                }
                else {
                    var thisNodeData = remarkData[remarkData.length - 1].data;
                    if (!value.trunkId) {
                        thisNodeData.push(this.translateItem(value, 0, additionalMsg));
                    } else {
                        var result = this.findInsertIndex(thisNodeData, value.trunkId);
                        if (result.index >= 0) {
                            thisNodeData.splice(result.index, 0, this.translateItem(value, result.lv, additionalMsg));
                        } else {
                            thisNodeData.push(this.translateItem(value, 0, additionalMsg));
                        }
                    }
                }
            }
        });
        return remarkData;
    }

     findInsertIndex(thisNodeData, trunkId) {
        let parentItem = null;
        let brotherItem = null;
        let tempItem = null;
        let j = -1,i;
        for (i = 0; i < thisNodeData.length; i++) {
            tempItem = thisNodeData[i];
            if (tempItem.id === trunkId) {
                parentItem = tempItem;
                j = i; //若没找到兄弟，则插入在上级的后面
            } else if (tempItem.trunkId === trunkId) {
                brotherItem = tempItem;
                j = i;
            }
        }

        if (parentItem !== null) {
            if (brotherItem === null) {
                return { index: j + 1, lv: parentItem.lv + 1};
            } else {
                //跳过兄弟的后代
                for (i = j + 1; i < thisNodeData.length; i++) {
                    tempItem = thisNodeData[i];
                    if (tempItem.lv > brotherItem.lv) {
                        j = i;
                    } else {
                        break;
                    }
                }
                return { index: j + 1, lv: parentItem.lv + 1 };
            }
        } else {
            return { index: -1, lv:0};
        }
    }


    translateItem(value, lv, additionalMsg): ITranslateItem {
        let additonalMsgArr = [];
        if (additionalMsg) {
            additionalMsg.forEach(msg=> {
                if (msg.taskId === value.id) {
                    additonalMsgArr.push(msg);
                }
            })
        }
        /*postLevel: value.postLevel,*/
        return {
            id: value.id,
            lv: lv,
            userName: value.userName,
            reply: value.reply,
            state: value.state,
            replyTime: value.replyTime ? this.timeFormat(value.replyTime) : null,             //留言时间
            markedTime: value.markedTime ? this.timeFormat(value.markedTime) : null,          //查看时间
            startTime: value.startTime ? this.timeFormat(value.startTime) : null,             //下达时间,
            finishedTime: value.finishedTime ? this.timeFormat(value.finishedTime) : null,    //办理时间,
            trunkId: value.trunkId,
            scheme: value.actionScheme,
            preOperatorId: value.preOperatorId,
            preStepId: value.preStepId,
            nodeId: value.nodeId,
            userInfo: value.userInfo,
            operationType: value.operationType,
            additonalMsgArr: additonalMsgArr,
            hasRead: value.hasRead
        };
    }

    getPassRoundData(arr: WorkFlowProcessDto[]): ITranslateItem[] {
        let remarkData = [];
        if (!arr) {
            return remarkData;
        }

        arr.forEach(value=>{
            if (value.operationType === 0) {
                remarkData.push(this.translateItem(value, 0,null));
            }
        });
        return remarkData;
    }

    /// 收文办件 会办意见
     getDealWithData(remarkData, relationships, additionalMsg, nodeIds) {
        if (!nodeIds) return [];
        if (!remarkData) return [];
        //var datas = JSON.parse(JSON.stringify(remarkData));

        let newRemarkData = [];
        remarkData.forEach(item => {
            if ((nodeIds.indexOf(item.nodeId) > -1 || item.signal2 == 'DisplayInHuiBan')
                && item.reply && item.operationType === 1
                && item.state !== 1 && !item.isHiddenInTable) {
                newRemarkData.push(item);
            }
        });

        if (additionalMsg && additionalMsg.length > 0) {
            newRemarkData = newRemarkData.concat(additionalMsg);
        }

        //依回复时间排序
        newRemarkData.sort((a, b) => {
            let aa, bb;
            if (a.finishedTime) {
                aa = Date.parse(a.finishedTime);
            } else if (a.replyTime) {
                aa = Date.parse(a.replyTime);
            }

            if (b.finishedTime) {
                bb = Date.parse(b.finishedTime);
            } else if (b.replyTime) {
                bb = Date.parse(b.replyTime);
            }
            return aa - bb;
        });

        //调整 主办、会办分管领导 的位置
        let newRemarkData2 = [];

        newRemarkData.forEach(item =>{
            let index, tempUserIds;
            if (item.signal && (item.signal === 'ZhuBanLeader' || item.signal === 'HuiBanLeader')) {
                tempUserIds = this.getResponsibilityUser(remarkData, relationships, item);
                index = -1;
                newRemarkData2.forEach((item2, index2) => {
                    if (tempUserIds.indexOf(item2.userId) > -1) {
                        index = index2;
                    }
                });
                if (index > -1) {
                    newRemarkData2.splice(index + 1, 0, item);
                } else {
                    newRemarkData2.push(item);
                }
            } else {
                newRemarkData2.push(item);
            }

            if (item.userInfo
                && (this._userHelper.isResponsibleLeader(item.userInfo) || this._userHelper.isMainLeaders(item.userInfo))
                && item.signal !== 'ZhuBan' && item.signal !== 'HuiBan') {
                item.isLeader = true;
            } else {
                item.isLeader = false;
            }
        });

        return newRemarkData2;
    }

     getResponsibilityUser(remarkData, relationships, task) {
        let tempUserIds = [];
        
        if (task.responsibilityId) {
            remarkData.forEach(item => {
                if (item.id === task.responsibilityId) {
                    tempUserIds.push(item.userId);
                }
            });
        }

        if (relationships) {
            relationships.forEach(item =>{
                if (item.taskId === task.id) {
                    remarkData.forEach(item2 => {
                        if (item2.id === item.responsibilityId) {
                            tempUserIds.push(item2.userId);
                        }
                    });
                }
            });
        }
        return tempUserIds;
    }
}